#!/bin/sh

BUILD_DIR=.

# clear toolchain
echo "BUILDER: remove old tool chain files ..."
rm -f "configure config.sub config.guess config.status"
rm -f "depcomp install-sh missing libtool ltmain.sh"
rm -f "aclocal.m4 config.h config.h.in"

# Remove all old Makefile.in
echo "BUILDER: remove old Makefile.in ..."
find . -name Makefile.in | xargs rm -f

# Rename configure.in, otherwise autoscan will read it and report errors
echo "BUILDER: rename configure.in to configure.in.bak ..."
mv configure.in configure.in.bak

# Tool autoscan:
# Input : src folders
# Output: configure.scan (manualy edit it to get configure.in)
echo "BUILDER: run autoscan ..."
autoscan 

# we can't directly use configure.scan. 
# we always copy our configure.in to build directory instead.
# so we MUST update configure.in manaully and keep it correct
echo "BUILDER: configure.scan is updated; compare it with configure.in.bak to create configure.in"
echo "BUILDER: remove configure.scan ..."
rm -f configure.scan

# rename configure.in back
echo "BUILDER: rename configure.in.bak back to configure.in ..."
mv configure.in.bak configure.in

# Tool autoheader
# Input : configure.in
# Output: config.h.in
echo "BUILDER: run autoheader ..."
autoheader --force 

# Tool aclocal
# Input : configure.in
# Output: aclocal.m4
echo "BUILDER: run aclocal ..."
aclocal --force

# Tool autoconf
# Input : aclocal.m4, configure.in
# Output: configure
echo "BUILDER: run autoconf ..."
autoconf --force 

# ltmain.sh is required by automake, but no tool can auto generate it. 
echo "BUILDER: installing ltmain.sh ..."

# TODO -- find a better way to get ltmain.sh
# UPDATE -- libtoolize can install ltmain.sh properly
#cp /usr/share/libtool/config/ltmain.sh .
libtoolize --force --copy

# Tool automake
# Input : configure.in, Makefile.am
# Output: Makefile.in, and other missing tools
echo "BUILDER: run automake ..."
automake --add-missing --copy

# remove useless files
echo "BUILDER: clean useless files ..."
rm -rf autom4te.cache autoscan.log config.log config.h.in~
